<template>
	<div class="system-role">
		<div class="top">
			<Row :gutter="10">
				<Col :span="4">
					<Input v-model="keyWord" placeholder="输入会员卡号/姓名/手机号码" />
				</Col>
				<Col :span="4">
					<Select placeholder="请选择患者类型" v-model="customerType">
						<Option
							v-for="item in diseaseTypeList"
							:value="item.id"
							:key="item.value"
						>{{ item.itemValue }}</Option>
					</Select>
				</Col>
				<Col :span="4">
					<DatePicker
                        style="width:100%;"
						type="datetimerange"
						:value="daterange"
						placement="top-start"
						placeholder="请选择随访时间范围"
                        @on-change="t=>daterange=t"
					/>
				</Col>
				<Col :span="4">
					<Button class="ml20" type="primary" @click="search">查询</Button>
					<Button class="ml20" type="default" plain @click="reset">清空</Button>
				</Col>
			</Row>
		</div>
		<Drawer :mask-closable="false" class="drawer" :title="alertTitle" v-model="showDrawer" :width="720">
			<!-- 查看的时候显示的内容 -->
			<b class="lh200">{{isShowCustomerInfo?'随访详情':'基本信息'}}</b>
			<Form :value="editedItem">
				<Row :gutter="32">
					<Col :span="12">
						<FormItem class="plain" label="姓名: " label-position="left">
							<span>{{curCustomer.customerName}}</span>
						</FormItem>
					</Col>
					<Col :span="12">
						<FormItem class="plain" label="年龄: " label-position="left">
							<span>{{curCustomer.birthday | AGE}}</span>
						</FormItem>
					</Col>
					<Col :span="12">
						<FormItem class="plain" label="性别: " label-position="left">
							<span v-if="Number(curCustomer.sex)===1">男</span>
							<span v-else-if="Number(curCustomer.sex)===2">女</span>
							<span v-else>-</span>
						</FormItem>
					</Col>
					<Col :span="12">
						<FormItem class="plain" label="手机号码: " label-position="left">
							<span>{{curCustomer.mobile}}</span>
						</FormItem>
					</Col>
					<Col :span="12">
						<FormItem class="plain" label="身份证号: " label-position="left">
							<span>{{curCustomer.customerInfo.idCard}}</span>
						</FormItem>
					</Col>
					<Col :span="12">
						<FormItem class="plain" label="档案编号: " label-position="left">
							<span>{{curCustomer.customerFileNumber}}</span>
						</FormItem>
					</Col>
					<Col :span="12">
						<FormItem class="plain" label="身高(cm): " label-position="left">
							<span>{{curCustomer.customerInfo.height}}</span>
						</FormItem>
					</Col>
					<Col :span="12">
						<FormItem class="plain" label="体重(kg): " label-position="left">
							<span>{{curCustomer.customerInfo.weight}}</span>
						</FormItem>
					</Col>
					<Col :span="12">
						<FormItem class="plain" label="BMI指数: " label-position="left">
							<span>{{bmi}}</span>
						</FormItem>
					</Col>
					<Col :span="12">
						<FormItem class="plain" label="患者类型: " label-position="left">
							<span>{{getCustomerType({customerType:curCustomer.customerInfo.diseaseType})}}</span>
						</FormItem>
					</Col>
					<Col :span="12">
						<FormItem class="plain" label="确诊时间: " label-position="left">
							<span>{{curCustomer.customerInfo.careTime}}</span>
						</FormItem>
					</Col>
					<Col :span="12">
						<FormItem class="plain" label="并发症: " label-position="left">
							<span>{{curCustomer.customerInfo.complication}}</span>
						</FormItem>
					</Col>
				</Row>
			</Form>
			<Divider />
			<b class="lh200">{{isShowCustomerInfo?'随访结果':'计划信息'}}</b>
			<Form :model="editedItem">
				<Row :gutter="32" v-show="isShowCustomerInfo">
					<Col :span="12">
						<FormItem class="plain" label="随访人员: " label-position="left">
							<span>{{editedItem.realUsername}}</span>
						</FormItem>
					</Col>
					<Col :span="12">
						<FormItem class="plain" label="随访时间: " label-position="left">
							<span>{{editedItem.realTime | YMDHMS}}</span>
						</FormItem>
					</Col>
					<Col :span="12">
						<FormItem class="plain" label="随访方式: " label-position="left">
							<span>待补充字段</span>
						</FormItem>
					</Col>
				</Row>

				<!-- 点击继续随访显示的内容 -->
				<Row v-if="isShowCustomerInfo===false" type="flex" :gutter="32">
					<Col :span="12">
						<FormItem type="flex" class="cube" label="计划人员:" label-position="left">
							<Select v-model="editedItem.planUserId" class="cube" placeholder="请选择计划人员">
								<Option
									class="select"
									v-for="item in userList"
									:value="item.id"
									:key="item.id"
								>{{ item.username }}</Option>
							</Select>
						</FormItem>
					</Col>
					<Col :span="12">
						<FormItem type="flex" class="cube" label="随访模板:" label-position="left">
							<Select v-model="editedItem.templateId" class="cube" placeholder="请选择随访模板">
								<Option
									class="select"
									v-for="item in templateFollowList"
									:value="item.id"
									:key="item.id"
								>{{ item.templateName }}</Option>
							</Select>
						</FormItem>
					</Col>
					<Col :span="12">
						<FormItem type="flex" class="cube" label="随访类型:" label-position="left">
							<Select v-model="editedItem.followType" class="cube" placeholder="请选择随访类型">
								<Option
									class="select"
									v-for="item in typeFollowList"
									:value="item.id"
									:key="item.id"
								>{{ item.itemValue }}</Option>
							</Select>
						</FormItem>
					</Col>
					<Col :span="12">
						<FormItem type="flex" class="cube" label="计划时间:" label-position="left">
							<DatePicker
                                @on-change="t=>editedItem.planTime=t"
								class="time-picker"
								:value="editedItem.planTime"
								type="datetime"
								placeholder="请选择计划时间"
							/>
						</FormItem>
					</Col>
					<Col :span="24">
						<FormItem label="随访内容:" label-position="left" prop="followContent">
							<Input class="cube" type="textarea" v-model="editedItem.followContent" placeholder />
						</FormItem>
					</Col>
				</Row>
			</Form>

			<Form :model="editedItem" :rules="rules"></Form>
			<div v-show="!isShowCustomerInfo" class="demo-drawer-footer">
				<Button style="margin-right: 8px" @click="close">取消</Button>
				<Button type="primary" :loading="editedIndex===-1?createLoading:updateLoading" @click="save">保存</Button>
			</div>
		</Drawer>
		<div>
			<div>
				<Table
					:loading="loading"
					highlight-row
					ref="currentRowTable"
					:columns="tableColumns"
					:data="items"
				>
					<template slot-scope="{ row }" slot="sex">
						<span v-if="Number(row.sex)===1">男</span>
						<span v-else-if="Number(row.sex)===2">女</span>
						<span v-else>-</span>
					</template>
					<template slot-scope="{row}" slot="createTime">
						<span>{{row.createTime | YMDHMS}}</span>
					</template>
					<template slot-scope="{row}" slot="planTime">
						<span>{{row.planTime | YMDHMS}}</span>
					</template>
                    <template slot-scope="{row}" slot="customerType">
						<span>{{getDiseaseType(row.customerType)}}</span>
					</template>

                    <template slot-scope="{row}" slot="followType">
                        <span>{{getFollowType(row)}}</span>
					</template>
                    
					<template slot-scope="{row}" slot="birthday">
						<span>{{row.birthday | YMD}}</span>
					</template>
					<template slot-scope="{row}" slot="realTime">
						<span>{{row.realTime | YMDHMS}}</span>
					</template>
					<template slot-scope="{row}" slot="updateTime">
						<span>{{row.updateTime | YMDHMS}}</span>
					</template>
					<template slot-scope="{row}" slot="action">
                        <a href="javascript:;" class="mr10" @click="customerGet(row)">查看</a>
                        <a href="javascript:;" class="mr10" @click="history(row)">历史</a>
                        <a href="javascript:;" class="mr10" @click="update(row)">继续随访</a>
					</template>
				</Table>
                <Row class="pagination">
                    <Col align="right">
                        <Page :current="page" :total="totalNum" show-total @on-change="pageChange" />
                    </Col>
                </Row>
			</div>
		</div>
	</div>
</template>
<script>
import { templateFollowAdd, templateFollowUpdate, templateFollowDelete } from '@api/followTemplate.js'
import { followAdd, followBatchAdd, followGet } from '@api/follow.js'

import { customerPageQueryFollowList } from '@api/customer.js'
import { customerGet } from '@api/customer.js'
import { dicGetItemByCode } from '@api/dic.js'
import { tagPageQueryList } from '@api/tag.js'
import { mapState } from '@lib/x_.js'
import moment from 'moment'
export default {
	data() {
		return {
            bmi: '',
			showDrawer: false,
			isShowCustomerInfo: false,
			loading: false,
			createLoading: false,
			updateLoading: false,
			removeLoading: false,
			editedIndex: -1,
			permissionIds: [],
			editedItem: {
				templateId: '',
				followType: '',
				customerId: '',
				followContent: '',
				planTime: '',
				planUserId: ''
			},
			defaultItem: {
				templateId: '',
				followType: '',
				customerId: '',
				followContent: '',
				planTime: '',
				planUserId: ''
			},
			curCustomer: {
				birthday: '',
				customerInfo: {
					idCard: '',
					careTime: ''
				}
			},

			// search,
			customerType: '',
			daterange: ['', ''],
			keyWord: '',

			items: [],
			page: 1,
			pageSize: 10,
			totalNum: 0,
			permissionList: [],
			totalTagList: [],
			tableColumns: [
				{
					align: 'left',
					width: 130,
					title: '档案编号',
					key: 'customerFileNumber'
				},
				{
					width: 130,
					title: '姓名',
					align: 'left',
					key: 'customerName'
				},
				{
					align: 'left',
					width: 100,
					title: '性别',
					slot: 'sex'
				},
				{
					width: 130,
					title: '年龄',
					align: 'left',
					slot: 'birthday'
				},
				{
					align: 'left',
					width: 170,
					title: '患者类型',
					slot: 'customerType'
				},
				{
					title: '随访类型',
					width: 130,
					align: 'left',
					slot: 'followType'
				},
				{
					title: '创建人',
					width: 130,
					align: 'left',
					key: 'createUsername'
				},
				{
					title: '创建时间',
					width: 170,
					align: 'left',
					slot: 'createTime'
				},
				{
					align: 'left',
					title: '计划时间',
					width: 170,
					slot: 'planTime'
				},
				{
					title: '随访人员',
					width: 130,
					align: 'left',
					key: 'realUsername'
				},
				{
					align: 'left',
					width: 170,
					title: '随访日期',
					slot: 'realTime'
				},
				{
					align: 'left',
					title: '操作',
					slot: 'action',
					width: 300
                },
                {
					title: ' ',
					key: '',
					align: '',
				}
			]
		}
	},
	mounted() {
		this.customerPageQueryFollowList()
		this.tagPageQueryList()
	},
	computed: {
		alertTitle() {
			if (this.isShowCustomerInfo) {
				return '随访详情'
			}
			return this.editedIndex === -1 ? '新增' : '继续随访'
        },
        ...mapState(['templateFollowList','typeFollowList','diseaseTypeList','familyList','diseaseHistoryList','familyHistoryList','nowTreatmentList','tagList','userList']),
	},
	methods: {
        getFollowType(row) {
            const { followType } = row;
            if (followType) {
                const idx = this.typeFollowList.findIndex((item,i) => String(item.id) === followType);
                return this.typeFollowList[idx] ? this.typeFollowList[idx]['itemValue'] : '-'
            }else {
                return '-'
            }
        },
        getCustomerType(row) {
			const { customerType } = row
			const { diseaseTypeList } = this
			const idx = diseaseTypeList.findIndex((item, i) => String(item.itemKey) === customerType)
			if (idx > -1) {
				return diseaseTypeList[idx]['itemValue']
			} else {
				return ''
			}
		},
        getDiseaseType(itemKey){
            const idx = this.diseaseTypeList.findIndex((item,i) => item.itemKey === itemKey)
            if (idx > -1) {
                return this.diseaseTypeList[idx]['itemValue']
            } else {
                return ''
            }
        },
		search() {
			this.page = 1
			this.pageSize = 10
			this.customerPageQueryFollowList()
		},
		reset() {
			this.page = 1
			this.pageSize = 10
			this.customerType = ''
			this.keyWord = ''
			this.daterange = ['','']
		},
		
		tagPageQueryList() {
			tagPageQueryList({ page: 1, pageSize: 1000 }).then(res => {
				if (res.code === '0') {
					this.totalTagList = res.data.items
				} else {
					this.$Modal.warning({
						title: '查询患者标签',
						content: res.errMsg || '查询错误'
					})
				}
			})
		},
		history(row) {
			this.$Modal.warning({
				title: '查询随访历史',
				content: '待完善'
            })
            const { userId } = row;
            followGet({id: userId}).then(res => {
                console.log('followGet res-->', res)
            })
            
		},
		customerGet(row) {
			const { userId } = row
			this.isShowCustomerInfo = true
			this.update(row)
		},
		pageChange(page) {
			if (this.loading) {
				return
			}
			this.page = page
			this.customerPageQueryFollowList()
		},
		update(item) {

            const { customerId} = item
			customerGet({ id: customerId }).then(res => {
				if (res.code === '0') {
                    this.curCustomer = Object.assign(this.curCustomer, res.data)
                    const { customerInfo } = this.curCustomer;
                    const { weight, height } = customerInfo || {}
                    if (weight && height) {
                        try {
                            this.bmi = Math.floor(Number(weight) /(Number(height) * Number(height)) * 10000);
                        } catch (error) {
                            
                        }
                    }
				} else {
					this.modal(res, '查询患者信息')
				}
			})
            this.editedIndex = item._index
            item.planTime = item.planTime || ''
            item.planTime = moment(item.planTime).format('YYYY-MM-DD HH:mm:ss')
			this.editedItem = Object.assign({}, item)
			this.showDrawer = true
		},
		create() {
			this.editedIndex = -1
			this.editedItem = Object.assign({}, this.defaultItem)
			this.showDrawer = true
		},
		remove(item, idx) {
			//done this.close();
			const { templateName, id } = item
			this.removeLoading || (this.removeLoading = true)
			this.$Modal.confirm({
				title: '删除',
				content: `是否删除模板: ${templateName}?`,
				onOk: async () => {
					const res = await customerPageQueryFollowList({ id })
					this.modal(res, '删除')
					this.customerPageQueryFollowList()
					this.$Modal.remove()
					this.removeLoading = false
				}
			})
		},
		async save() {
			if (this.editedIndex > -1) {
				const { userId, templateId, followType, followContent, planTime, planUserId } = this.editedItem
				this.updateLoading || (this.updateLoading = true)
				const res = await followAdd({ customerId: userId, templateId, followType, followContent, planTime, planUserId })
				this.updateLoading = false
				this.modal(res, '继续随访')
				//create
			} else {
				const { userId, templateId, followType, followContent, planTime, planUserId } = this.editedItem
				this.updateLoading || (this.updateLoading = true)
				const res = await followAdd({ customerId: userId, templateId, followType, followContent, planTime, planUserId })
				this.updateLoading = false
				this.modal(res, '继续随访')
				//create
			}
			this.customerPageQueryFollowList()
			this.close()
		},
		modal(res, title) {
			if (res.code === '0') {
				this.$Modal.success({
					title: title || this.alertTitle,
					content: res.data
				})
			} else {
				this.$Modal.warning({
					title: title || this.alertTitle,
					content: res.errMsg
				})
			}
		},
		close() {
			this.showDrawer = false
			this.isShowCustomerInfo = false
			this.curCustomer = {
				birthday: '',
				customerInfo: {
					idCard: '',
					careTime: ''
				}
			}
			setTimeout(() => {
				this.editedItem = Object.assign({}, this.defaultItem)
				this.editedIndex = -1
			}, 10)
		},
		customerPageQueryFollowList() {
			const { keyWord, customerType, daterange, page, pageSize, loading } = this
			const [beginTime, endTime] = daterange;
			const obj = { beginTime, endTime, customerType, keyWord, page, pageSize }
			if (loading) return
			this.loading = true
			customerPageQueryFollowList(obj)
				.then(res => {
					this.loading = false
					console.log('res roles->', res)
					if (res.code === '0') {
						const { currentPage, isMore, items, pageSize, totalNum, totalPage } = res.data
						;(this.items = items), (this.page = currentPage), (this.totalNum = totalNum)
						console.log('this.items->', this.items)
					} else {
						this.$Modal.warning({
							title: '查询列表',
							content: res.errMsg
						})
					}
				})
				.catch(err => {
					this.loading = false
				})
		}
	},
	watch: {
		showDrawer(after) {
			after || this.close()
        },
	}
}
</script>
<style scoped lang='scss'>
.drawer {
	.ivu-select {
		width: auto;
		min-width: 250px;
	}
	.time-picker {
		min-width: 250px;
	}
	.cube {
		max-width: 600px;
	}
}
.system-role {
	background-color: #fff;
}

</style>